<template>
	<view class="spare-part-apply-form-page" :style="pageStyle">
		<view class="content">
			<view class="select-material-bar" @click="handleSelectMaterialClick">
				<view class="title">
					<view class="dot">*</view>
					<view class="text">选择配件</view>
				</view>

				<view class="btn">
					<uni-icons type="plus" color="#007cff" size="17"></uni-icons>
					<text>添加</text>
					<uni-icons type="right" color="#007cff" size="17"></uni-icons>
				</view>
			</view>

			<view
				class="selected-material-list"
				v-if="materialSelectedList.length >= 1"
			>
				<view
					class="selected-material-item"
					v-for="(
						selectedMaterialOption, selectedMaterialOptionIndex
					) in materialSelectedList"
					:key="selectedMaterialOptionIndex"
				>
					<view class="cover-info">
						<view class="cover">
							<uni-icons color="#aac" size="48" type="image"></uni-icons>
						</view>
						<view class="info">
							<view class="info-item">
								<view class="info-item-label">品牌:</view>
								<view class="info-item-value">
									{{ selectedMaterialOption.brand }}
								</view>
							</view>
							<view class="info-item">
								<view class="info-item-label">编号:</view>
								<view class="info-item-value">
									{{ selectedMaterialOption.spareCode }}
								</view>
							</view>
							<view class="info-item">
								<view class="info-item-label">名称:</view>
								<view class="info-item-value">
									{{ selectedMaterialOption.spareName }}
								</view>
							</view>
							<view class="info-item">
								<view class="info-item-label">图号(同步SAP):</view>
								<view class="info-item-value">
									{{ selectedMaterialOption.spareModel }}
								</view>
							</view>
							<view class="info-item">
								<view class="info-item-label">规格:</view>
								<view class="info-item-value">
									{{ selectedMaterialOption.specName }}
								</view>
							</view>
							<view class="info-item">
								<view class="info-item-label">单价:</view>
								<view class="info-item-value">
									￥{{ (selectedMaterialOption.price || 0).toFixed(2) }}
								</view>
							</view>
							<view class="info-item">
								<view class="info-item-label">申请数量:</view>
								<view class="info-item-value">
									<uni-number-box
										:max="9999999999"
										v-model="selectedMaterialOption.applyQty"
									/>
								</view>
							</view>
							<view class="info-item">
								<view class="info-item-label">金额:</view>
								<view class="info-item-value">
									￥{{
										(
											(selectedMaterialOption.price || 0) *
											selectedMaterialOption.applyQty
										).toFixed(2)
									}}
								</view>
							</view>
						</view>
					</view>
					<view class="btn">
						<uni-icons
							type="minus-filled"
							size="30"
							color="#f56c6c"
							@click="
								handleRemoveClick(
									selectedMaterialOption.spareId,
									selectedMaterialOption.specId,
								)
							"
						></uni-icons>
					</view>
				</view>
			</view>

			<view class="form">
				<view class="form-item">
					<view class="form-item-label">收货仓</view>
					<view class="form-item-value">
						{{ engineerStore.enableStore ? engineerStore.storeName : '无仓库' }}
					</view>
				</view>
				<view class="form-item">
					<view class="form-item-label">收货联系人</view>
					<view class="form-item-value">{{ addPartsVo.receiveUsername }}</view>
				</view>
				<view class="form-item">
					<view class="form-item-label">
						<span style="color: #f56c6c;">*</span>
						联系手机
					</view>
					<view class="form-item-value">
						<uni-easyinput
							placeholder="请输入联系手机"
							v-model.trim="addPartsVo.receiveUserPhone"
							class="phone-input"
						/>
					</view>
				</view>
				<view class="form-item receive-address">
					<view class="form-item-label">收货地址</view>
					<view class="form-item-value">
						<AreaAddress ref="addressRef" :address_obj="addressValue" />
					</view>
				</view>
				<view class="form-item detail-address">
					<view class="form-item-label">详细地址</view>
					<view class="form-item-value">
						<uni-easyinput
							type="textarea"
							:maxlength="100"
							placeholder="请输入详细地址"
							v-model.trim="addPartsVo.receiveAddress"
						/>
					</view>
				</view>
				<view class="form-item remark">
					<view class="form-item-label">单据备注</view>
					<view class="form-item-value">
						<uni-easyinput
							type="textarea"
							:maxlength="100"
							v-model.trim="addPartsVo.remark"
							placeholder="填写备注"
						></uni-easyinput>
					</view>
				</view>
			</view>
		</view>

		<view class="footer">
			<view
				v-if="engineerStore.enableStore"
				class="btn submit-btn-enable"
				@click="submitFun(2)"
			>
				保存并提交
			</view>
			<view class="btn submit-save-btn-disabled" v-else>保存并提交</view>
			<view
				v-if="engineerStore.enableStore"
				class="btn save-btn-enable"
				@click="submitFun(1)"
			>
				保存
			</view>
			<view class="btn submit-save-btn-disabled" v-else>保存</view>
		</view>
	</view>
</template>

<script setup lang="ts">
	import {ref, onMounted, reactive, watch, nextTick, computed} from 'vue';
	import _ from 'lodash';
	import store from '@/store_network/index.js';
	import {onUnload, onShow, onLoad, onHide} from '@dcloudio/uni-app';
	import AreaAddress from '@/components/u-network/AreaAddress.vue';
	import apiParts from '@/util/network_api/parts.js';
	import useSparePartApplyMaterialSelectedListService from './services/useSparePartApplyMaterialSelectedListService';
	import {SparePartListItem} from './types';
	import {useStockCheckBeforeSparePartApplyFormSubmitService} from './services/useSparePartApplyForm';
	import apiUser from '@/util/network_api/user.js';
	import useSparePartApplyDetail from './services/useSparePartApplyDetail';

	const {sparePartAPplyDetail, getSparePartApplyDetail} =
		useSparePartApplyDetail();
	const {stockCheckForm, stockCheckResult, stockCheck} =
		useStockCheckBeforeSparePartApplyFormSubmitService();
	const {
		materialSelectedList,
		removeSelectedMaterial,
		clearMaterialSelectedList,
		addSelectedMaterial,
	} = useSparePartApplyMaterialSelectedListService();

	const pageStyle = computed(() => {
		const systemInfo = uni.getSystemInfoSync();
		return {
			height: `${systemInfo.windowHeight - systemInfo.safeAreaInsets.bottom}px`,
			width: `${systemInfo.windowWidth}px`,
		};
	});

	const addressRef = ref();

	const engineerStore = ref<{
		address: string;
		area: string;
		city: string;
		enableStore: boolean;
		province: string;
		storeId: string;
		storeName: string;
		userPhone: string;
		username: string;
	}>({
		address: '',
		area: '',
		city: '',
		enableStore: false,
		province: '',
		storeId: '',
		storeName: '',
		userPhone: '',
		username: '',
	});

	const addressValue = ref({
		province: '',
		city: '',
		area: '',
		town: '',
	});

	const currentAccountNetworkId = ref('');
	const sparePartApplyId = ref('');

	const handleRemoveClick = (spareId: string, specId: string) => {
		removeSelectedMaterial(spareId, specId);
	};

	const handleSelectMaterialClick = () => {
		uni.navigateTo({
			url: '/pages_network/home/parts/selectParts',
		});
	};

	const addPartsVo = ref({
		materialVos: [],
		receiveAddress: '',
		receiveArea: '',
		receiveCity: '',
		receiveProvince: '',
		receiveStoreId: '',
		receiveUserPhone: '',
		receiveUsername: '',
		remark: '',
	});

	const create = async (status: 1 | 2, type: 1 | 2 | 3) => {
		uni.showLoading({
			mask: true,
			title: '加载中',
		});
		const res = await apiParts.createSparePartApply({
			area: addPartsVo.value.receiveArea,
			city: addPartsVo.value.receiveCity,
			code: sparePartAPplyDetail.value.code,
			contactName: engineerStore.value.username,
			contactPhone: engineerStore.value.userPhone,
			createType: 1,
			detailAddress: addPartsVo.value.receiveAddress,
			id: sparePartApplyId.value,
			networkId: currentAccountNetworkId.value,
			orderRemark: addPartsVo.value.remark,
			province: addPartsVo.value.receiveProvince,
			receivingStoreId: engineerStore.value.storeId,
			shippingStoreId: '',
			status,
			town: '',
			type,
			materialApplyParamList: materialSelectedList.value.map((item) => {
				return {
					actualQty: 0,
					id: '',
					isBoom: item.isBom,
					isSufficient: item.stock >= item.applyQty ? 1 : 0,
					materialRemark: '',
					price: item.price,
					qty: item.applyQty,
					spareCode: item.spareCode,
					spareId: item.spareId,
					urgency: 1,
					warehouse: '',
				};
			}),
		});
		uni.hideLoading();
		if (res.code === 20000) {
			uni.showModal({
				title: '提示',
				content: '操作成功',
				success(param) {
					if (param.confirm) {
						addPartsVo.value = {
							materialVos: [],
							receiveAddress: '',
							receiveArea: '',
							receiveCity: '',
							receiveProvince: '',
							receiveStoreId: '',
							receiveUserPhone: '',
							receiveUsername: '',
							remark: '',
						};
						clearMaterialSelectedList();
						uni.redirectTo({
							url: '/pages_network/home/parts/partsList',
						});
					}
				},
			});
		}
	};

	// 提交
	const submitFun = _.debounce(
		async (status: 1 | 2) => {
			if (!engineerStore.value.enableStore) {
				uni.showModal({
					title: '提示',
					content: '无个人仓,无法申请',
				});
				return;
			}
			if (materialSelectedList.value.length == 0) {
				uni.showModal({
					title: '提示',
					content: '请选择配件',
				});
				return;
			}
			if (!addPartsVo.value.receiveUserPhone) {
				uni.showModal({
					title: '提示',
					content: '请输入联系手机',
				});
				return;
			}
			
			let {province, city, area} = addressRef.value.address;
			addPartsVo.value.receiveProvince = province;
			addPartsVo.value.receiveCity = city;
			addPartsVo.value.receiveArea = area;
			if (!addPartsVo.value.receiveProvince) {
				uni.showModal({
					title: '提示',
					content: '请选择地址',
				});
				return;
			}

			if (!addPartsVo.value.receiveAddress) {
				uni.showModal({
					title: '提示',
					content: '请填写详细地址',
				});
				return;
			}

			try {
				uni.showLoading({
					title: '加载中...',
					mask: true,
				});

				stockCheckForm.value.networkId = currentAccountNetworkId.value;
				materialSelectedList.value.forEach((material) => {
					stockCheckForm.value.materialQty[material.spareCode] =
						material.applyQty;
				});

				if (status === 1) {
					create(status, stockCheckResult.value.type);
					return;
				}

				await stockCheck();
				const tipMsg: Array<string> = [];
				if (stockCheckResult.value.isSufficient === 0) {
					tipMsg.push(stockCheckResult.value.difference + '申请量大于可用量');
				}

				if (stockCheckResult.value.type === 1) {
					tipMsg.push('该申请单为收费单据');
				}

				if (tipMsg.length >= 1) {
					uni.showModal({
						title: '提示',
						content: tipMsg.join('并且') + '，确定要继续提交吗？',
						success(res) {
							if (res.confirm) {
								create(status, stockCheckResult.value.type);
							}

							if (res.cancel) {
								uni.hideLoading();
							}
						},
					});

					return;
				}

				create(status, stockCheckResult.value.type);
			} catch (e) {}
			uni.hideLoading();
		},
		600,
		{leading: false},
	);

	const getEngineerStore = async () => {
		try {
			uni.showLoading({
				mask: true,
				title: '加载中',
			});
			const res = await apiParts.getEngineerStore();
			uni.hideLoading();
			if (res.code === 20000) {
				engineerStore.value = res.data.row;
				addPartsVo.value.receiveUsername = res.data.row.username;
				addPartsVo.value.receiveStoreId = res.data.row.storeId;
				addPartsVo.value.receiveAddress = res.data.row.address;
				addPartsVo.value.receiveUserPhone = res.data.row.userPhone;
				addressValue.value = {
					province: res.data.row.province,
					city: res.data.row.city,
					area: res.data.row.area,
					town: res.data.row.town,
				};
			}
		} catch (e) {
			uni.hideLoading();
		}
	};

	const getCurrentNetworkInfo = async () => {
		const res = await apiUser.getUerDetail();
		if (res.code === 20000) {
			currentAccountNetworkId.value = res.data.row.row.networkId;
		}
	};

	const init = async () => {
		uni.showLoading({
			mask: true,
			title: '加载中',
		});
		await getCurrentNetworkInfo();
		await getEngineerStore();
		if (sparePartApplyId.value) {
			await getSparePartApplyDetail(sparePartApplyId.value);
			addPartsVo.value = {
				materialVos: [],
				receiveAddress: sparePartAPplyDetail.value.detailAddress,
				receiveArea: sparePartAPplyDetail.value.area,
				receiveCity: sparePartAPplyDetail.value.city,
				receiveProvince: sparePartAPplyDetail.value.province,
				receiveStoreId: sparePartAPplyDetail.value.receivingStoreId,
				receiveUserPhone: sparePartAPplyDetail.value.contactPhone,
				receiveUsername: sparePartAPplyDetail.value.contactName,
				remark: sparePartAPplyDetail.value.orderRemark,
			};
			sparePartAPplyDetail.value.materialApplyVoList.forEach((item) => {
				addSelectedMaterial({
					id: item.id,
					spareCode: item.spareCode,
					spareId: item.spareId,
					spareName: item.spareName,
					applyQty: item.qty,
					actualSendQty: item.actualQty,
					spareModel: '',
					specId: item.specId,
					specName: item.specName,
					type: item.goodsType,
					unit: item.spareUnit,
					price: item.price,
					remark: item.materialRemark,
					urgentLevel: item.urgency,
					stock: (Number(item.storeQty) || 0) - (item.freezeQty || 0),
					isBom: item.isBoom,
					brand: item.brandName,
				});
			});
		}
		uni.hideLoading();
	};

	onLoad((e) => {
		if (e.id) {
			sparePartApplyId.value = e.id;
		}
		init();
	});
</script>

<style lang="scss" scoped>
	.spare-part-apply-form-page {
		display: flex;
		flex-direction: column;
		overflow: hidden;
		background-color: #f5f5f5;
		overflow: auto;

		.content {
			flex: 1;
			height: 0;
			overflow: auto;

			.select-material-bar {
				margin: 24rpx 24rpx 0 24rpx;
				display: flex;
				justify-content: space-between;
				background-color: #fff;
				padding: 18rpx;
				box-shadow: 0 0 10rpx rgba(0, 0, 0, 0.1);
				align-items: center;
				border-radius: 8rpx;

				.title {
					display: flex;
					align-items: center;

					.dot {
						font-size: 28rpx;
						color: #f56c6c;
					}

					.text {
						color: #606266;
						font-size: 24rpx;
					}
				}

				.btn {
					display: flex;
					align-items: center;
					font-size: 24rpx;
					color: #007cff;
				}
			}

			.selected-material-list {
				margin: 24rpx 24rpx 0 24rpx;
				display: flex;
				flex-direction: column;
				row-gap: 24rpx;

				.selected-material-item {
					display: flex;
					box-shadow: 0 0 10rpx rgba(0, 0, 0, 0.1);
					box-sizing: border-box;
					padding: 18rpx;
					background-color: #fff;
					border-radius: 8rpx;
					justify-content: space-between;

					.cover-info {
						display: flex;
						column-gap: 12rpx;

						.cover {
							min-width: 124rpx;
							min-height: 124rpx;
							max-width: 124rpx;
							max-height: 124rpx;
							border: 2rpx solid #eee;
						}

						.info {
							display: flex;
							flex-direction: column;

							.info-item {
								display: flex;
								font-size: 24rpx;
								column-gap: 12rpx;

								.info-item-label {
									color: #606266;
									white-space: nowrap;
								}
							}
						}
					}
				}
			}

			.form {
				display: flex;
				background-color: #fff;
				padding: 18rpx;
				margin: 24rpx;
				box-shadow: 0 0 10rpx rgba(0, 0, 0, 0.1);
				flex-direction: column;
				row-gap: 12rpx;
				border-radius: 8rpx;

				.form-item {
					display: flex;
					justify-content: space-between;
					font-size: 24rpx;
					width: 100%;
					height: fit-content;

					.form-item-label {
						height: 48rpx;
						line-height: 48rpx;
						color: #606266;
						white-space: nowrap;
					}

					.form-item-value {
						.phone-input {
							width: 534rpx;

							:deep(.uni-easyinput__content) {
								border-left: none;
								border-right: none;
								border-top: none;

								.uni-easyinput__content-input {
									padding: 0 !important;
									height: 48rpx;
								}
							}
						}
					}
				}

				.detail-address,
				.remark {
					flex-direction: column;
					row-gap: 8rpx;
				}

				.receive-address {
					column-gap: 36rpx;

					.form-item-value {
						width: 100%;

						:deep(.btn_input) {
							display: flex;
							align-items: center;

							.uni-icons {
								top: 0;
								bottom: 0;
							}

							.show_input {
								border-bottom: 2rpx solid rgb(229, 229, 229);
								box-sizing: border-box;
								height: 48rpx;
							}

							.input_val {
								font-size: 24rpx !important;
								padding: 0;
								height: 48rpx;
								line-height: 48rpx;
							}
						}
					}
				}
			}
		}

		.footer {
			width: 100%;
			padding: 24rpx;
			box-sizing: border-box;
			background-color: #fff;
			display: flex;
			column-gap: 24rpx;

			.btn {
				width: 100%;
				height: 72rpx;
				color: #fff;
				display: flex;
				justify-content: center;
				align-items: center;
				border-radius: 72rpx;
				font-size: 24rpx;
			}

			.submit-btn-enable {
				background-color: #e69103;
			}

			.submit-save-btn-disabled {
				background-color: #eee;
			}

			.save-btn-enable {
				background-color: #007cff;
			}
		}
	}
</style>